<?php
include("../header.inc");
require_once("../DataBase.inc");
require_once("../applicants/view_script.inc");
require_once("exam_queries.inc");

$exam_center_id = $_GET["exam_center_id"];

function parse_time($str) {
	$i = strpos($str, ":");
	if ($i === false) $i = strpos($str, "h");
	if ($i === false) { $h = $str; $m = "0"; }
	else { $h = substr($str, 0, $i); $m = substr($str, $i+1); }
	if (!ctype_digit($h) || !ctype_digit($m)) return null;
	return array(intval($h),intval($m));
}

if (isset($_GET["remove_room"])) {
	$room = $_GET["remove_room"];
	DataBase::delete("exam_center_rooms",array("exam_center_id"=>$exam_center_id,"room"=>$room));
	DataBase::update("applicant_exam_room_beta", array("exam_center_id"=>$exam_center_id,"room_number"=>$room), array("room_number"=>NULL,"exam_id"=>NULL));
	$res = DataBase::query("SELECT * FROM supervisor LEFT JOIN exam ON exam.exam_id=supervisor.exam_id WHERE room='".mysql_escape_string($room)."' AND exam_center_id=".$exam_center_id);
	if ($res <> false)
		foreach ($res as $r)
			DataBase::delete("supervisor",array("exam_id"=>$r["exam_id"],"room"=>$room));
} else if (isset($_POST["new_exam_date"])) {
	$date = $_POST["new_exam_date"];
	$today = getdate();
	$today = mktime(0,0,0,$today["mon"],$today["mday"],$today["year"]);
	$date = strtotime($date);
	if ($date < $today) echo "<div style='color:red'>Invalid date: cannot plan an exam in the past!</div>";
	else {
		$start_time = parse_time($_POST["new_exam_start_time"]);
		$end_time = parse_time($_POST["new_exam_end_time"]);
		if ($start_time === null || $end_time === null) echo "<div style='color:red'>Invalid time: format is hh:mm</div>";
		else if ($end_time[0] < $start_time[0] || ($end_time[0] == $start_time[0] && $end_time[1]<=$start_time[1])) echo "<div style='color:red'>The end time is before the start time !</div>";
		else {
			$date = date("Y-m-d", $date);
			$start_time = $start_time[0].":".$start_time[1].":00";
			$end_time = $end_time[0].":".$end_time[1].":00";
			$res = DataBase::query("SELECT * FROM exam WHERE selection_campaign_id=".$_SESSION["campaign_id"]." AND exam_center_id=".$exam_center_id." AND date='".$date."' AND ((exam_start_time>='".$start_time."' AND exam_start_time<'".$end_time."') OR (exam_end_time>='".$start_time."' AND exam_end_time<'".$end_time."') OR (exam_start_time<'".$start_time."' AND exam_end_time>='".$end_time."'))");
			if ($res <> false && count($res)>0) echo "<div style='color:red'>An exam already exist at this date and time</div>";
			else
				DataBase::insert("exam", array("exam_center_id"=>$exam_center_id,"selection_campaign_id"=>$_SESSION["campaign_id"],"exam_date"=>$date,"exam_start_time"=>$start_time,"exam_end_time"=>$end_time));
		}
	}
} else if (isset($_GET["remove_exam"])) {
	$exam_id = $_GET["remove_exam"];
	DataBase::delete("exam",array("exam_id"=>$exam_id));
	DataBase::update("applicant_exam_room_beta", array("exam_center_id"=>$exam_center_id,"exam_id"=>$exam_id), array("room_number"=>NULL,"exam_id"=>NULL));
	DataBase::delete("supervisor",array("exam_id"=>$exam_id));
} else if (isset($_GET["unassign"])) {
	DataBase::update("applicant_exam_room_beta", array("exam_center_id"=>$exam_center_id,"applicant_id"=>$_GET["unassign"]), array("room_number"=>NULL,"exam_id"=>NULL));
}

$rooms_query = "SELECT * FROM exam_center_rooms WHERE exam_center_id=".$exam_center_id;
$rooms = DataBase::query($rooms_query);
if ($rooms === false) $rooms = array();

$exams_query = "SELECT * FROM exam WHERE exam_center_id=".$exam_center_id." AND selection_campaign_id=".$_SESSION["campaign_id"];
$exams = DataBase::query($exams_query);
if ($exams === false) $exams = array();

if (isset($_POST["room"]) && isset($_POST["capacity"])) {
	if (trim($_POST["room"])=="") {
		echo "<span style='color:red'>Room cannot be created because you didn't enter a room number. Please try again.</span><br/>";
	} else if (!is_numeric($_POST["capacity"])) {
		echo "<span style='color:red'>Room cannot be created/updated because the room capacity is not valid. Please try again.</span><br/>";
	} else {
		$exists = false;
		if ($rooms <> null)
			foreach ($rooms as $room) if ($room["room"] == $_POST["room"]) { $exists = true; break; }
		if ($exists) {
			DataBase::update("exam_center_rooms",array("exam_center_id"=>$exam_center_id,"room"=>$_POST["room"]),array("capacity"=>$_POST["capacity"]));
		} else {
			DataBase::insert("exam_center_rooms",array("exam_center_id"=>$exam_center_id,"room"=>$_POST["room"],"capacity"=>$_POST["capacity"]));
		}
		$rooms = DataBase::query($rooms_query);
	}
} else if (isset($_GET["assign_room"])) {
	$room = $_GET["assign_room"];
	$nb = intval($_POST["nb"]);
	$max = intval($_GET["max"]);
	if ($nb > $max) $nb = $max;
	$exam_id = $_GET["exam_id"];
	$query = "SELECT applicant.applicant_id FROM applicant";
	$query .= " LEFT JOIN applicant_exam_room_beta ON applicant_exam_room_beta.applicant_id=applicant.applicant_id";
	$query .= " WHERE applicant.selection_campaign_id=".$_SESSION["campaign_id"]." AND applicant.excluded=0 AND applicant_exam_room_beta.exam_center_id=".$exam_center_id." AND applicant_exam_room_beta.room_number IS NULL LIMIT ".$nb;
	$result = DataBase::query($query);
	if ($result <> false && count($result)>0) {
		$query = "UPDATE applicant_exam_room_beta SET room_number='".mysql_escape_string($room)."', exam_id=".$exam_id." WHERE";
		$first = true;
		foreach ($result as $r) {
			if ($first) $first = false; else $query .= " OR";
			$query .= " applicant_id=".$r["applicant_id"];
		}
		DataBase::query($query);
	}
} else if (isset($_POST["supervisor"])) {
	$room = $_POST["room"];
	$supervisor = $_POST["supervisor"];
	$exam_id = $_POST["exam_id"];
	DataBase::insert("supervisor",array("exam_id"=>$exam_id,"room"=>$room,"supervisor_username"=>$supervisor));
} else if (isset($_GET["remove_supervisor"])) {
	$room = $_GET["room"];
	$supervisor = $_GET["remove_supervisor"];
	$exam_id = $_GET["exam_id"];
	DataBase::delete("supervisor",array("exam_id"=>$exam_id,"room"=>$room,"supervisor_username"=>$supervisor));
}		

$exam_center = query_exam_centers_info($exam_center_id)->execute();

$non_assigned = query_applicants_without_exam_plan($exam_center_id)->execute();
if ($non_assigned == false) $non_assigned = array();
$nb_non_assigned = count($non_assigned);
?>
<h1>Exam Plan</h1>
<br/>
<a href='review_exam_centers.php'>Go back to the list of exam centers</a><br/>
<br/>
Exam Center: <b><?php echo $exam_center[0]["exam_center_name"]?></b> (Province <b><?php echo $exam_center[0]["province_name"]?></b>)<br/>
<br/>
<div style='border: 1px solid black; padding:2px'>
<b>Available rooms in this center:</b>
<?php
if ($rooms == false || count($rooms) == 0)
	echo "<span style='color:red'>No room defined yet</span><br/>";
else {?>
<table border=1 style='border-collapse:collapse;empty-cells:show'>
<tr>
 <th style='background-color:#C0C0C0'></th>
 <th style='background-color:#C0C0C0'>Room number</th>
 <th style='background-color:#C0C0C0'>Room capacity</th>
</tr>
<?php
foreach ($rooms as $room) {
	echo "<tr>";
	echo "<td><a href='?exam_center_id=".$exam_center_id."&remove_room=".urlencode($room["room"])."' title='Remove this room'><img src='".$_SESSION["root_url"]."/images/trash.gif' border=0/></a></td>";
	echo "<td>".$room["room"]."</td>";
	echo "<td>".$room["capacity"]."</td>";
	echo "</tr>";
}
?>
</table>
<?php } ?>
<form action="?exam_center_id=<?php echo $exam_center_id?>" method="post">
<b>Create a new room or change the capacity:</b><br/>
Room number: <input type='text' size=10 maxlength=3 name='room' onkeyup="javascript: data_change(this)"/>
<!--Room capacity: <input type='text' size=10 maxlength=10 name='capacity' onkeydown='return validate_int(this,event);'/><br/>-->
Room capacity: <input type='text' size=10 maxlength=3 name='capacity'  onkeyup="javascript: data_change(this)" /><br/>
<button type='submit'>Ok</button>
</form>
</div>
<br/>

<?php 
$assigned_by_date = array();
if (count($rooms)>0) {?>

<div style='border: 1px solid black; padding:2px'>
<b>Exams plan in this center:</b></br>
<table border=1 style='border-collapse:collapse;empty-cells:show'>
<tr>
 <th style='background-color:#C0C0C0'></th>
 <th style='background-color:#C0C0C0'>Date</th>
 <th style='background-color:#C0C0C0'>Start Time</th>
 <th style='background-color:#C0C0C0'>End Time</th>
 <th style='background-color:#C0C0C0'>Room number</th>
 <th style='background-color:#C0C0C0'>Room capacity</th>
 <th style='background-color:#C0C0C0'>Assigned applicants</th>
 <th style='background-color:#C0C0C0'>Action</th>
 <th style='background-color:#C0C0C0'>Supervisor</th>
 <th style='background-color:#C0C0C0'>Action</th>
</tr>
<?php
foreach ($exams as $exam) {
	echo "<tr>";
	echo "<td rowspan=".count($rooms)."><a href='?exam_center_id=".$exam_center_id."&remove_exam=".$exam["exam_id"]."' title='Remove this exam'><img src='".$_SESSION["root_url"]."/images/trash.gif' border=0/></a></td>";
	echo "<td rowspan=".count($rooms)." valign='top'>".$exam["exam_date"]."</td>";
	echo "<td rowspan=".count($rooms)." valign='top'>".$exam["exam_start_time"]."</td>";
	echo "<td rowspan=".count($rooms)." valign='top'>".$exam["exam_end_time"]."</td>";
	if (!isset($assigned_by_date[$exam["exam_date"]])) $assigned_by_date[$exam["exam_date"]] = array();
	if (!isset($assigned_by_date[$exam["exam_date"]][$exam["exam_start_time"]])) $assigned_by_date[$exam["exam_date"]][$exam["exam_start_time"]] = array();
	for ($room_index = 0; $room_index < count($rooms); $room_index++) {
		$room = $rooms[$room_index];
		if ($room_index > 0) echo "<tr>";
		echo "<td>".$room["room"]."</td>";
		echo "<td>".$room["capacity"]."</td>";
		$result = query_applicants_with_exam_plan($exam_center_id, $room["room"], $exam["exam_id"])->execute();
		if ($result == false) $result = array();
		$assigned_by_date[$exam["exam_date"]][$exam["exam_start_time"]][$room["room"]] = $result;
		$nb_assigned = count($result);
		echo "<td>";
		echo $nb_assigned." applicant(s)";
		echo "</td>";
		echo "<td nowrap='nowrap'>";
		if ($nb_assigned < $room["capacity"]) {
			$remaining = $room["capacity"] - $nb_assigned;
			echo $remaining." remaining place(s).";
			$possible = $nb_non_assigned < $remaining ? $nb_non_assigned : $remaining;
			if ($nb_non_assigned > 0) {
				echo "<form style='margin:0px;padding:0px' action='?exam_center_id=".$exam_center_id."&assign_room=".$room["room"]."&max=".$possible."&exam_id=".$exam["exam_id"]."' method='post'>";
				echo "Assign ";
				echo "<input type='text' name='nb' value='".$possible."' size=4 maxlength=4 onkeydown='return validate_int(this,event)'/>";
				echo " applicants (max: ".$possible.")";
				echo "<button type='submit' style='margin:0px;padding:0px'>Ok</button>";
				echo "</form>";
				//echo " <a href='?exam_center_id=".$exam_center_id."&assign_room=".$room["room"]."&nb=".$possible."&exam_id=".$exam["exam_id"]."'>Assign ".$possible." applicant(s)</a>";
			}
		} else if ($nb_assigned == $room["capacity"]) {
			echo "Room full";
		} else {
			echo "<span style='color:red'>Too many applicants assigned !!</span>";
		}
		echo "</td>";
		$result = query_exam_supervisors($exam_center_id, $room["room"], $exam["exam_id"])->execute();
		if ($result == false || count($result)==0) {
			echo "<td style='color:red'>";
			echo "Nobody";
			echo "</td>";
		} else {
			echo "<td nowrap='nowrap'>";
			foreach ($result as $r) {
				echo $r["first_name"]." ".$r["last_name"];
				echo "<a href='?remove_supervisor=".$r["username"]."&exam_center_id=".$exam_center_id."&room=".urlencode($room["room"])."&exam_id=".$exam["exam_id"]."'><img src='".$_SESSION["root_url"]."/images/small_remove.gif' hspace=0 vspace=0 style='vertical-align:middle' border=0/></a><br/>";
			}
			echo "</td>";
		}
		echo "<td nowrap='nowrap'>";
		echo "<a href='assign_supervisor.php?exam_center_id=".$exam_center_id."&room=".urlencode($room["room"])."&exam_id=".$exam["exam_id"]."'><img src='".$_SESSION["root_url"]."/images/user.gif' hspace=1 vspace=0 style='vertical-align:bottom' border=0/>Assign supervisor</a>";
		echo "<a href='../applicants.php?view=print_display_exam_list&exam_center_id=".$exam_center_id."&room=".urlencode($room["room"])."&date=".urlencode($exam["exam_date"])."&time=".urlencode($exam["exam_start_time"])."'><img src='".$_SESSION["root_url"]."/images/print.gif' hspace=1 vspace=0 style='vertical-align:bottom' border=0/>Print display/attendance list</a>";
		echo "</td>";
		echo "</tr>";
	}
}
?>
</table>
<?php
if ($nb_non_assigned > 0) {
	echo "Info: <span style='color:red'><i>".$nb_non_assigned." applicant(s) are assigned to this exam center but have no exam date/room number assigned.</i></span><br/>";
} else {
	echo "Info: <span style='color:green'><i>all applicants for this exam center have a room number assigned.</i></span><br/>";
}
$q = query_applicants_with_exam_plan($exam_center_id);
if ($rooms <> false)
foreach ($rooms as $room) $q->where("room_number<>'".$room["room"]."'");
$result = $q->count();
if ($result > 0) {
	echo "Info: <i>".$result." applicant(s) are assigned to this exam center and are assigned to a non-existing room number.</i><br/>";
	echo " &nbsp; &nbsp; <a href='' onclick='edit_manually();return false'>View list of applicants and edit rooms manually</a><br/>";
}
?>
<br/>
<form name='new_exam' action='?exam_center_id=<?php echo $exam_center_id?>' method='post'>
Plan a new exam in this center on 
<input type='text' size=10 readonly='readonly' name='new_exam_date' onclick="displayDatePicker('new_exam_date')"/>
 from <input type='text' size=5 name='new_exam_start_time'/> to <input type='text' size=5 name='new_exam_end_time'/><br/>
<button type="submit">Create this new exam</button>
</form>
</div>
<?php } ?>
<br/>

<br/>
<?php
if ($nb_non_assigned > 0) {
echo "List of applicants not yet assigned to an exam:<br/>";
echo "<table cellspacing=0 cellpadding=0 border=1 style='border:1px solid black;border-collapse:collapse'><tr><th>ID<th><th>First Name</th><th>Last Name</th><th>Khmer Name</th><th>Sex</th></tr>";
foreach ($non_assigned as $a) {
	echo "<tr>";
	echo "<td>".$a["applicant_selection_id"]."</td>";
	echo "<td>".$a["applicant_firstname"]."</td>";
	echo "<td>".$a["applicant_lastname"]."</td>";
	echo "<td>".$a["applicant_khmer_name"]."</td>";
	echo "<td>".$a["sex"]."</td>";
	echo "</tr>";
}
echo "</table>";
}
?>
List of applicants assigned to an exam:
<table cellspacing=0 cellpadding=0 border=1 style='border:1px solid black;border-collapse:collapse'>
<tr><th>Date</th><th>Start Time</th><th>Room</th><th>ID</th><th>First Name</th><th>Last Name</th><th>Khmer Name</th><th>Sex</th><th></th></tr>
<?php
foreach ($assigned_by_date as $date=>$list_date) {
	foreach ($list_date as $time=>$list_time) {
		foreach ($list_time as $room=>$applicants) {
			if (count($applicants)==0) continue;
			echo "<tr>";
			echo "<td rowspan=".count($applicants)." valign='top' align='center'>".$date."</td>";
			echo "<td rowspan=".count($applicants)." valign='top' align='center'>".$time."</td>";
			echo "<td rowspan=".count($applicants)." valign='top' align='center'>".$room."</td>";
			$first = true;
			foreach ($applicants as $a) {
				if ($first) $first = false; else echo "<tr>";
				echo "<td>".$a["applicant_selection_id"]."</td>";
				echo "<td>".$a["applicant_firstname"]."</td>";
				echo "<td>".$a["applicant_lastname"]."</td>";
				echo "<td>".$a["applicant_khmer_name"]."</td>";
				echo "<td>".$a["sex"]."</td>";
				echo "<td><a href='?exam_center_id=".$exam_center_id."&unassign=".$a["applicant_id"]."'>Unassign</a></td>";
				echo "</tr>";
			}
		}
	}
}
?>
</table>
	
<?php include '../field_validators.inc' ?>